package com.gitee.feizns.quickstart.web.Interceptors.bucket4j.handler;

import com.gitee.feizns.quickstart.web.Interceptors.bucket4j.RateLimitException;
import com.gitee.feizns.quickstart.web.Interceptors.bucket4j.RateLimitHandler;
import com.gitee.feizns.quickstart.web.WebUtils;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.BandwidthBuilder;
import io.github.bucket4j.Bucket;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Objects;

/**
 * 防重复请求（一秒一次）
 * @author feizns
 * @since 2025/10/28
 */
public class NoRepeat implements RateLimitHandler {

    /**
     * 带宽
     */
    private final Bandwidth bandwidth;

    public NoRepeat(Bandwidth bandwidth) {
        this.bandwidth = bandwidth;
    }

    public NoRepeat() {
        this(BandwidthBuilder.builder().capacity(1).refillIntervally(1, Duration.ofSeconds(1)).build());
    }

    @Override
    public Bucket bucket(String key) {
        return Bucket.builder().addLimit(bandwidth).build();
    }

    @Override
    public String key() {
        HttpServletRequest req = WebUtils.getReq();
        String method = req.getMethod();
        String path = WebUtils.getReq().getRequestURI();
        String query = Objects.toString(req.getQueryString(), "");
        String userAgent = WebUtils.getUserAgent();
        String body = WebUtils.getRequestBodyAsString();
        String ip = WebUtils.getIpAddress();
        return RateLimitHandler.md5(method, path, query, userAgent, body, ip);
    }

    @Override
    public void throwIfExceeded(Bucket bucket) {
        if ( !bucket.tryConsume(1) )
            throw new RateLimitException("请勿重复请求！");
    }

}
